package main

import "fmt"

//var lastOccured = make([]int, 0xffff) // 用数组来优化map，放在外面用于优化垃圾回收

func lengthOfNonRepeatingSubStr(s string) int {
	lastOccured := make(map[rune]int) // 改为rune一个中文算一个rune；map存在hash冲突需要解决
	// stores last occurred pos + 1.
	// 0 means not seen.
	//for i := range lastOccured {
	//	lastOccured[i] = 0 // 清理数组, 时间消耗最大
	//}
	start := 0
	maxLength := 0
	for i, ch := range []rune(s) { // s转rune的过程中进行了utf8解码的过程
		//fmt.Println(i)
		if LastI, ok := lastOccured[ch]; ok && LastI >= start {
			//fmt.Println("LastI", start)
			start = lastOccured[ch] + 1 // 记录同样的元素之前的下标
			//fmt.Println("start", start)
		}
		if i-start+1 > maxLength {
			maxLength = i - start + 1 // 记录无重复的长度
			//fmt.Println("max",maxLength)
		}
		lastOccured[ch] = i //
	}

	return maxLength
}

func main() {
	fmt.Println(lengthOfNonRepeatingSubStr("abcdabcde"))
	fmt.Println(lengthOfNonRepeatingSubStr("你好呀呀呀呀"))
}
